import 'package:mmkv/mmkv.dart';

import '../../flutter_base_lib.dart';

class MK {
  MK._();

  static final _mmkv = MMKV.defaultMMKV();

  /// 写入缓存
  /// [key] 缓存Key
  /// [obj] 缓存内容
  /// 写入无需管Type
  static void encode(String key, dynamic obj) {
    if (obj == null) {
      return;
    }
    if (obj is String) {
      _mmkv.encodeString(key, obj);
    } else if (obj is bool) {
      _mmkv.encodeBool(key, obj);
    } else if (obj is int) {
      _mmkv.encodeInt(key, obj);
    } else if (obj is int) {
      _mmkv.encodeInt32(key, obj);
    } else if (obj is double) {
      _mmkv.encodeDouble(key, obj);
    }
  }

  ///读取Int缓存
  ///[key] 缓存Key
  ///[defaultValue] 默认值 0
  static int getInt(String key, {int defaultValue = 0}) {
    return _mmkv.decodeInt(key, defaultValue: defaultValue);
  }

  ///读取Double缓存
  ///[key] 缓存Key
  ///[defaultValue] 默认值 0
  static double getDouble(String key, {double defaultValue = 0}) {
    return _mmkv.decodeDouble(key, defaultValue: defaultValue);
  }

  ///读取Int32缓存
  ///[key] 缓存Key
  ///[defaultValue] 默认值 0
  static int getInt32(String key, {int defaultValue = 0}) {
    return _mmkv.decodeInt32(key, defaultValue: defaultValue);
  }

  ///读取Bool缓存
  ///[key] 缓存Key
  ///[defaultValue] 默认值 false
  static bool getBool(String key, {bool defaultValue = false}) {
    return _mmkv.decodeBool(key, defaultValue: defaultValue);
  }

  ///读取String缓存
  ///[key] 缓存Key
  ///[defaultValue] 默认值 ""
  static String getString(String key, {String defaultValue = ""}) {
    var s = _mmkv.decodeString(key);
    if (s == null || s.isEmpty) {
      return "";
    } else {
      return s;
    }
  }

  ///清理多个缓存
  ///[keys] 缓存Key列表
  static void removeKeys(List<String> keys) {
    return _mmkv.removeValues(keys);
  }

  ///清空缓存
  static void clear() {
    _mmkv.clearAll();
  }
}

void main() {
  var data = "Test";
  const String key = "KEY_TEST";
  MK.encode(key, data);
  var cache = MK.getString(key);
  M7Log.d(tag: "ChawLoo", msg: "读取的缓存::$cache");
  var cacheWithDefault = MK.getString("#123123#", defaultValue: "TestDefault");
  M7Log.d(tag: "ChawLoo", msg: "读取的缓存::$cacheWithDefault");
}
